const Router = require('koa-router');
const common = require('../../libs/common');

// toDon
let router = new Router;

// 主页
router.get('/', async ctx => {
    // 获取轮播图
    let banners = await ctx.db.query('SELECT * FROM banner_table ORDER BY serial ASC')
    // 获取分类
    let catalogs = await ctx.db.query('SELECT * FROM catalog_table');
    // 获取文章
    let articles = await ctx.db.query(`
        SELECT *, 
        article_table.title AS article_title,   
        catalog_table.title AS catalog_title,
        article_table.ID AS article_ID  
        FROM article_table 
        LEFT JOIN catalog_table ON article_table.catalog_ID = catalog_table.ID
        ORDER BY article_table.created_time DESC LIMIT 10
    `);

    articles.forEach(article => {
        let oDate = new Date(article.created_time * 1000);
        article.created_time = `${oDate.getFullYear()}-${common.toDon(oDate.getMonth() + 1)}-${common.toDon(oDate.getDate())}`
    })

    await ctx.render('www/index',{
        HTTP_ROOT:ctx.config.HTTP_ROOT,
        banners,
        catalogs,
        articles
    })
})

// 文章分类
router.get('/list/:id', async ctx => {
    let {id} = ctx.params;
    let {HTTP_ROOT} = ctx.config;

    // 查询分类
    let rows = await ctx.db.query('SELECT * FROM catalog_table WHERE ID=?',id);
    // 查询分类下对应文章
    let articles = await ctx.db.query(`
        SELECT *, 
        article_table.title AS article_title,   
        catalog_table.title AS catalog_title,
        article_table.ID AS article_ID  
        FROM article_table 
        LEFT JOIN catalog_table ON article_table.catalog_ID = catalog_table.ID
        WHERE article_table.catalog_ID = ${id}
        ORDER BY article_table.created_time DESC LIMIT 10
    `);
    articles.forEach(article => {
        let oDate = new Date(article.created_time * 1000);
        article.created_time = `${oDate.getFullYear()}-${common.toDon(oDate.getMonth() + 1)}-${common.toDon(oDate.getDate())}`
    })

    await ctx.render('www/list',{
        HTTP_ROOT:ctx.config.HTTP_ROOT,
        catalog_title:rows[0].title,
        articles
    })

})


// 文章详情
router.get('/article/:id', async ctx => {
    let {id} = ctx.params;
    let {HTTP_ROOT} = ctx.config;
    var article = await ctx.db.query('SELECT * FROM article_table WHERE ID=?',id)
    article = article[0]
    let oDate = new Date(article.created_time * 1000);
    article.created_time = `${oDate.getFullYear()}-${common.toDon(oDate.getMonth() + 1)}-${common.toDon(oDate.getDate())}`

    await ctx.render('www/show',{
        HTTP_ROOT:ctx.config.HTTP_ROOT,
        article
    })
})

// 导出路由
module.exports = router.routes();